﻿using pdftron.PDF.Annots;
using System;
using Windows.UI.Xaml.Controls;

using PDFRect = pdftron.PDF.Rect;

namespace pdftron.PDF.Tools.Utilities
{
    public class NoteDialogBase : UserControl
    {
        protected IMarkup _Annotation;
        protected PDFViewCtrl _PDFViewCtrl;
        protected ToolManager _ToolManager;
        protected int _AnnotPageNumber = 0;

        public NoteDialogBase()
        {

        }

        public NoteDialogBase(IMarkup annotation, PDFViewCtrl ctrl, ToolManager toolManager, int annotPageNumber)
        {
            _Annotation = annotation;
            _PDFViewCtrl = ctrl;
            _ToolManager = toolManager;
            _AnnotPageNumber = annotPageNumber;
        }

        public virtual void Close()
        {
            // override to close
        }

        protected string GetTextFromAnnot()
        {
            try
            {
                _PDFViewCtrl.DocLockRead();
                string text = _Annotation.GetContents();
                if (text != null)
                {
                    return text;
                }
            }
            catch (Exception)
            {

            }
            finally
            {
                _PDFViewCtrl.DocUnlockRead();
            }

            return "";
        }

        protected void SetAnnotText(string text)
        {
            try
            {
                _PDFViewCtrl.DocLock(true);

                PDFRect rect = _Annotation.GetRect();
                rect.Normalize();
                // We need to give this a larger rect, else it won't show up properly in adobe reader.
                pdftron.PDF.Annots.Popup pop = pdftron.PDF.Annots.Popup.Create(_PDFViewCtrl.GetDoc().GetSDFDoc(), new PDFRect(rect.x2 + 50, rect.y2 + 50, rect.x2 + 200, rect.y2 + 200));
                pop.SetParent(_Annotation);
                _Annotation.SetPopup(pop);
                _Annotation.SetContents(text);

                _ToolManager.CurrentTool.SetAuthor(_Annotation);

                Page page = _Annotation.GetPage();
                page.AnnotPushBack(pop);
            }
            catch (Exception)
            {
            }
            finally
            {
                _PDFViewCtrl.DocUnlock();
            }
        }

        protected void DeleteAnnot()
        {
            try
            {
                _PDFViewCtrl.DocLock(true);
                Page page = _PDFViewCtrl.GetDoc().GetPage(_AnnotPageNumber);
                page.AnnotRemove(_Annotation);
                _PDFViewCtrl.UpdateWithAnnot(_Annotation, _AnnotPageNumber);

            }
            catch (Exception)
            {
            }
            finally
            {
                _PDFViewCtrl.DocUnlock();
                _Annotation = null;
            }
        }

    }
}
